package com.google.wave.api.samples;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import com.google.wave.api.*;

public class UrloidyServlet extends AbstractRobotServlet {
	private static Logger log = Logger.getLogger(UrloidyServlet.class);

	@Override
	public void processEvents(RobotMessageBundle bundle) {
		Wavelet wavelet = bundle.getWavelet();

		if (bundle.wasSelfAdded()) {
			Blip blip = wavelet.appendBlip();
			TextView textView = blip.getDocument();
			textView
					.append("Hello from Urloidy! I'll try to be useful in this conversation offering shortend urls alternatives to the urls that you insert in your conversation!");
		}

		log.debug("wavelet called! id: " + wavelet.getWaveletId() + " title: "
				+ wavelet.getTitle());
		for (Event e : bundle.getEvents()) {
			if (e.getType() == EventType.BLIP_SUBMITTED) {
				Blip blip = e.getBlip();
				TextView textView = blip.getDocument();
				String blipText = textView.getText();
				String convertedText = convertText(new StringBuffer(blipText))
						.toString();
				if (convertedText.length() > 0) {
					blip.createChild().getDocument().append(convertedText);
				}
			}
		}
	}

	public StringBuffer convertText(StringBuffer initialText) {
		StringBuffer strb = new StringBuffer();
		StringBuffer result = new StringBuffer(initialText.length());
		Pattern p = Pattern
				.compile("(@)?(http://)?[a-zA-Z_0-9\\-]+(\\.\\w[a-zA-Z_0-9\\-]+)+(/[&amp;\\n\\-=?\\+\\%/\\.\\w]+)?");
		Matcher m = p.matcher(initialText);
		while (m.find()) {
			String href = m.group();
			if (href.startsWith("@")) {
				continue;
			}
			if (href.startsWith("http://urloid")) {
				continue;
			}
			String tinyUrl = shortenUrl(href);
			if (tinyUrl != null) {
				strb.append(tinyUrl);
				strb.append("\n");
				m.appendReplacement(result, "" + tinyUrl + "\n");
			}
		}
		m.appendTail(result);
		if (strb.length() > 0)
			strb.insert(0, "You can use this shortend url(s):\n");
		return strb;
	}

	private String shortenUrl(String href) {
		String url = "http://urloid.com/api/?url=" + href + "&amp;mask=small";
		String response = UrlFetcher.fetchUrl(url);
		return (response.startsWith("http://urloid.com/")) ? response : null;
	}

}
